<?php

namespace app\api\controller;

use addons\epay\library\Service;
use app\api\model\RushOrderAddress;
use app\api\model\RushTime;
use app\api\model\UserAddress;
use app\api\model\RushGoods;
use app\api\model\RushOrder;
use app\api\model\RushOrderEntrust;
use app\api\model\UserCoupon;
use app\common\controller\Api;
use app\common\model\ScoreLog;
use app\common\model\User;
use think\Cache;
use think\Db;
use think\Exception;
use think\exception\PDOException;

/**
 * 抢购-买家仓库
 */
class RushBuyer extends Api
{
    protected $noNeedLogin = ['cancelAction','entrustNotify','entrustNotifyAction','takeoverCancelAction'];
    protected $noNeedRight = '*';

    /**
     * @ApiTitle    (列表)
     * @ApiMethod   (GET)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name=type, type=integer, required=true, description="订单类型:all=全部,waitpay=待付款,waitget=待确认收款,waitup=待上架,takeover=已提货")
     * @ApiReturn   ({
        "code": 1,
        "msg": "",
        "time": "1652233114",
        "data": {
            "total": 1, //数据总数
            "per_page": 15,
            "current_page": 1,
            "last_page": 1,
            "data": [{ //列表
                "id": 3, //订单ID
                "order_no": "R2022051154100974", //订单号
                "order_status": "0", //订单状态:0=待付款,1=待确认收款,2=待委托上架（待提货）,3=买家已委托上架,4=已提货
                "rushtime": "2022-05-21 20:10:20", //抢购时间
                "goods_name": "商品一", //商品名称
                "goods_price": "7000.00", //商品价格
                "goods_no": "123", //商品编码
                "goods_image": "http://petsdemo.qiniu.brofirst.cn/uploads/20220508/13cb1b8e54988cbb3710cc79897f0096.jpg", //封面图
                "time_name": "狂欢上午场", //所属场次
                "seller": { //交易方
                    "id": 1000, //ID
                    "nickname": "Xue", //昵称
                    "avatar": "", //头像
                    "url": "/u/1000"
                },
                "order_status_text": "Order_status 0", //订单状态文字
                "complain_status_text": "Complain_status 0"
            }]
        }
    })
     */
    public function list()
    {
        $type = $this->request->param('type');
        $where = [
            'buyer_id' => $this->auth->id,
            'order_status' => ['neq','3'], //不展示已上架订单
        ];
        switch ($type){
            case 'all':
                break;
            case 'waitpay':
                $where['order_status'] = '0';
                break;
            case 'waitget':
                $where['order_status'] = '1';
                break;
            case 'waitup':
                $where['order_status'] = '2';
                break;
            case 'takeover':
                $where['order_status'] = '4';
                break;
            default:
                $this->error('参数不合法');
        }
        $table_name = RushOrder::getTable();
        $list = RushOrder::with(['seller'])
            ->where($where)
            ->order($table_name.'.rushtime desc')
            ->paginate()
            ->each(function($v){
                $v->visible(['id','order_no','order_status','rushtime','goods_name','goods_no','goods_image','goods_price','time_name','seller']);
                //支付倒计时，50分钟
                $lefttime = 60 * 50 - (time() - $v['rushtime']);
                $v->paycountdown = $lefttime > 0 ? $lefttime : 0;
                $v->append(['paycountdown']);
                //抢购时间
                $v->rushtime = !empty($v['rushtime']) ? date('Y-m-d H:i:s',$v['rushtime']) : '';
                //交易方
                $v->getRelation('seller')->visible(['id','avatar','nickname']);
            });
        $this->success('',$list);
    }

    /**
     * @ApiTitle    (查看卖家凭证)
     * @ApiMethod   (GET)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name=order_id, type=integer, required=true, description="订单ID")
     * @ApiReturn   ({
        "code": 1,
        "msg": "",
        "time": "1652233699",
        "data": {
            "id": 1000, //用户ID
            "nickname": "Xue", //用户名
            "bank_name": null, //所属银行
            "bank_card_no": null, //银行卡号
            "bank_card_holder": null, //银行卡持卡人
            "goods_price": "7000.00", //支付金额
            "url": "/u/1000"
        }
    })
     */
    public function sellerBankCard()
    {
        $order_id = $this->request->param('order_id');
        empty($order_id) && $this->error('请选择订单');
        $order = RushOrder::where('buyer_id',$this->auth->id)->where('id',$order_id)->field('id,order_status,seller_id,goods_price')->find();
        empty($order) && $this->error('订单不存在');
        $order['order_status'] != '0' && $this->error('订单不合法');
        $seller = User::where('id',$order['seller_id'])->field('id,nickname,bank_name,bank_card_no,bank_card_holder')->find();
        $seller['goods_price'] = $order['goods_price'];
        $this->success('',$seller);
    }

    /**
     * @ApiTitle    (取消订单)
     * @ApiMethod   (GET)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name=order_id, type=integer, required=true, description="订单ID")
     * @ApiReturn   ({
    "code":"状态码",
    "msg": "提示消息"
    })
     */
    public function cancel()
    {
        $order_id = $this->request->param('order_id');
        empty($order_id) && $this->error('请选择订单');
        $order = RushOrder::where('buyer_id',$this->auth->id)->where('id',$order_id)->field('id,order_status,goods_id,payment_voucher')->find();
        empty($order) && $this->error('订单不存在');
        $order['order_status'] != '0' && $this->error('订单不合法');
        $res = self::cancelAction($order);
        $res['code'] == 0 && $this->error($res['msg']);
        $this->success('成功');
    }

    /**
     * 取消订单操作
     * @ApiInternal
     */
    public static function cancelAction($order)
    {
        \think\Log::write('取消订单操作：'.json_encode($order));
        Db::startTrans();
        try {
            //订单状态变为：已上架
            $order->save(['order_status' => '3','buyer_id'=>0,'payment_voucher'=>'','rushtime'=>0]);
            //商品状态变为：上架
            RushGoods::where('id',$order['goods_id'])->update(['status' => '1']);
            //删除待结算积分
            ScoreLog::where('rush_order_id',$order['id'])->where('is_settled','0')->delete();
            Db::commit();
        }catch (PDOException $e){
            Db::rollback();
            return ['code' => 0,'msg' => $e->getMessage()];
        }catch (Exception $e){
            Db::rollback();
            return ['code' => 0,'msg' => $e->getMessage()];
        }
        return ['code' => 1,'msg' => '取消成功'];
    }

    /**
     * @ApiTitle    (上传付款凭证)
     * @ApiMethod   (POST)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name=order_id, type=integer, required=true, description="订单ID")
     * @ApiParams   (name=payment_voucher, type=string, required=true, description="上传凭证，多图片用英文逗号隔开")
     * @ApiReturn   ({
    "code":"状态码",
    "msg": "提示消息"
    })
     */
    public function paymentVoucherUpload()
    {
        $order_id = $this->request->param('order_id');
        $payment_voucher = $this->request->param('payment_voucher');
        empty($order_id) && $this->error('请选择订单');
        empty($payment_voucher) && $this->error('请上传支付凭证');
        $order = RushOrder::where('buyer_id',$this->auth->id)->where('id',$order_id)->field('id,order_status,payment_voucher')->find();
        empty($order) && $this->error('订单不存在');
        $order['order_status'] != '0' && $this->error('订单不合法');
        $order->save(['payment_voucher' => $payment_voucher]);
        $this->success('');
    }

    /**
     * @ApiTitle    (查看付款凭证)
     * @ApiMethod   (GET)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name=order_id, type=integer, required=true, description="订单ID")
     * @ApiReturn   ({
        "code": 1,
        "msg": "",
        "time": "1652233954",
        "data": {
            "id": 3,
            "order_status": "0",
            "payment_voucher": [ //凭证组图
                "http://petsdemo.qiniu.brofirst.cn123",
                "http://petsdemo.qiniu.brofirst.cn456"
            ],
            "order_status_text": "Order_status 0",
            "complain_status_text": ""
        }
    })
     */
    public function paymentVoucherView()
    {
        $order_id = $this->request->param('order_id');
        empty($order_id) && $this->error('请选择订单');
        $order = RushOrder::where('buyer_id',$this->auth->id)->where('id',$order_id)->field('id,order_status,payment_voucher')->find();
        empty($order) && $this->error('订单不存在');
        !in_array($order['order_status'],['0','1','2']) && $this->error('订单不合法');
        $this->success('',$order);
    }

    /**
     * @ApiTitle    (支付确认)
     * @ApiMethod   (GET)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name=order_id, type=integer, required=true, description="订单ID")
     * @ApiReturn   ({
    "code":"状态码",
    "msg": "提示消息"
    })
     */
    public function confirmPay()
    {
        $order_id = $this->request->param('order_id');
        empty($order_id) && $this->error('请选择订单');
        $order = RushOrder::where('buyer_id',$this->auth->id)->where('id',$order_id)->find();
        empty($order) && $this->error('订单不存在');
        
        //用缓存3秒，防止连点
        Cache::get('confirm_pay_'.$order_id) && $this->error('订单不合法');
        Cache::set('confirm_pay_'.$order_id,'1',3);

        $order['order_status'] != '0' && $this->error('订单不合法');
        empty($order['payment_voucher']) && $this->error('请先上传支付凭证');
        $res = self::confirmPayAction($order);
        $res['code'] == 0 && $this->error($res['msg']);
        $this->success('成功');
    }

    /**
     * 支付确认操作
     * @ApiInternal
     */
    public static function confirmPayAction($order)
    {
        Db::startTrans();
        try{

            //订单状态变为：待确认收款
            $order->save(['order_status' => '1']);
            //商品关联的订单用户信息相应修改
            RushGoods::where('id',$order['goods_id'])->update(['current_order_id' => $order['id'],'buyer_id'=>$order['buyer_id']]);

            //分销计算
            $buyer = User::where('id',$order['buyer_id'])->field('inviter_id')->find();
            //一级分销
            if($buyer['inviter_id'] > 0){
                $inviter = User::where('id',$buyer['inviter_id'])->field('id,inviter_id,score')->find();
                if($inviter){
                    $firstscore = round($order['goods_price'] * (config('site.first_commission_rate') / 100));
                    ScoreLog::create([
                        'user_id' => $inviter['id'],
                        'lower_user_id' => $order['buyer_id'],
                        'score' => $firstscore,
                        'before' => $inviter['score'],
                        'after' => $inviter['score']+$firstscore,
                        'rush_order_id' => $order['id'],
                        'rush_order_no' => $order['order_no'],
                    ]);
                    //二级分销
                    if($inviter['inviter_id'] > 0) {
                        $inviter_parent = User::where('id', $inviter['inviter_id'])->field('id,score')->find();
                        if($inviter_parent) {
                            $secondscore = round($order['goods_price'] * (config('site.second_commission_rate') / 100));
                            ScoreLog::create([
                                'user_id' => $inviter_parent['id'],
                                'lower_user_id' => $order['buyer_id'],
                                'score' => $secondscore,
                                'before' => $inviter_parent['score'],
                                'after' => $inviter_parent['score'] + $secondscore,
                                'rush_order_id' => $order['id'],
                                'rush_order_no' => $order['order_no'],
                            ]);
                        }
                    }
                }
            }

            //删除重复的队列记录，（订单逻辑不同于其他项目，所以需要删除）
            $payload = json_encode([
                'job' => "\\app\\api\\job\\RushOrderAutoOper@autoConfirmGetMoney",
                'data' => ['order_id'=>$order['id']],
            ]);
            Db::name('jobs')->where('payload',$payload)->delete();
            // 卖家超过2小时未确认收款的，将会自动确认收款
            $confirm_minue = 120;
            \think\Queue::later(($confirm_minue * 60), '\app\api\job\RushOrderAutoOper@autoConfirmGetMoney', ['order_id' => $order['id']], 'rushbuy');

            Db::commit();
        }catch (PDOException $e){
            Db::rollback();
            return ['code' => 0,'msg' => $e->getMessage()];
        }catch (Exception $e){
            Db::rollback();
            return ['code' => 0,'msg' => $e->getMessage()];
        }
        return ['code' => 1,'msg' => '确认支付成功'];
    }

    /**
     * @ApiTitle    (委托上架-展示)
     * @ApiMethod   (GET)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name=order_id, type=integer, required=true, description="订单ID")
     * @ApiReturn   ({
        "code": 1,
        "msg": "",
        "time": "1652254547",
        "data": {
            "order": {
                "id": 3, //订单ID
                "order_no": "R2022051154100974", //订单号
                "order_status": "0", //订单状态:0=待付款,1=待确认收款,2=待委托上架（待提货）,3=买家已委托上架,4=已提货,5=已上架转移
                "goods_name": "商品一", //商品名称
                "goods_price": "7000.00", //商品价格
                "goods_image": "http://petsdemo.qiniu.brofirst.cn/uploads/20220508/13cb1b8e54988cbb3710cc79897f0096.jpg", //封面图
                "time_name": "狂欢上午场", //所属场次
                "seller": { //交易方
                    "id": 1000, //ID
                    "nickname": "Xue", //昵称
                    "avatar": "", //头像
                    "url": "/u/1000"
                },
                "order_status_text": "待上架", //订单状态文字
                "complain_status_text": "未投诉" //投诉状态文字
            },
            "entrust_price": 7280, //委托价格
            "service_fee": 140, //手续费
        }
    })
     */
    public function entrustView()
    {
        $order_id = $this->request->param('order_id');
        empty($order_id) && $this->error('请选择订单');
        $order = RushOrder::where('buyer_id',$this->auth->id)->where('id',$order_id)->find();
        empty($order) && $this->error('订单不存在');
        $order['order_status'] != '2' && $this->error('订单不合法');
        $entrust_rate = config('site.entrust_rate');
        $entrust_price = round($order['goods_price'] * (1+$entrust_rate/100),2);
        $service_rate = config('site.service_rate');
        $service_fee = round($order['goods_price'] * ($service_rate/100),2);
        $order->visible(['id','order_no','order_status','goods_name','goods_image','goods_price','time_name','seller']);
        $order['seller']->visible(['id','avatar','nickname']);
        $this->success('',compact('order','entrust_price','service_fee'));
    }

    /**
     * @ApiTitle    (委托上架-获取优惠券)
     * @ApiMethod   (GET)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name=order_id, type=integer, required=true, description="订单ID")
     * @ApiReturn   ({
        "code": 1,
        "msg": "",
        "time": "1652251449",
        "data": [{ //列表
            "id": 1, //ID
            "name": "1", //名称
            "price": "10.00", //金额
            "bottom_price": "140.00", //使用门槛
            "start_time": 0,
            "end_time": 1653011802,
            "validity_time": "1970年01月01日—2022年05月20日" //有效期
        }]
    })
     */
    public function couponList()
    {
        $order_id = $this->request->param('order_id');
        empty($order_id) && $this->error('请选择订单');
        $order = RushOrder::where('buyer_id',$this->auth->id)->where('id',$order_id)->find();
        empty($order) && $this->error('订单不存在');
        $order['order_status'] != '2' && $this->error('订单不合法');
        $service_rate = config('site.service_rate');
        $service_fee = $order['goods_price'] * ($service_rate/100);
        $list = UserCoupon::where('user_id',$this->auth->id)
            ->where('end_time','>',time())
            ->where('status',1)
            ->where('bottom_price','<=',$service_fee)
            ->field('id,name,price,bottom_price,start_time,end_time')
            ->select();
        $this->success('',$list);
    }

    /**
     * @ApiTitle    (委托上架)
     * @ApiMethod   (POST)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name=order_id, type=integer, required=true, description="订单ID")
     * @ApiParams   (name=openid, type=string, required=false, description="openid")
     * @ApiParams   (name=entrust_price, type=string, required=false, description="上架价格")
     * @ApiParams   (name=user_coupon_id, type=integer, required=false, description="用户优惠券ID")
     * @ApiReturn   ({
    "code":"状态码",
    "msg": "提示消息"
    })
     */
    public function entrust()
    {
        $order_id = $this->request->param('order_id');
        $openid = $this->request->param('openid');
        $entrust_price = $this->request->param('entrust_price');
        $user_coupon_id = $this->request->param('user_coupon_id',0);
        empty($order_id) && $this->error('请选择订单');
        $order = RushOrder::where('buyer_id',$this->auth->id)->where('id',$order_id)->find();
        empty($order) && $this->error('订单不存在');
        $order['order_status'] != '2' && $this->error('订单不合法');
        //买家订单变为待上架 状态后，加一个判定，两小时后才可点击上架。
        time() < ($order['confirmtime']+7200) && $this->error('确认收款后，两小时后才可上架');
        //上架价格
        $entrust_rate = config('site.entrust_rate');
        $entrust_price_cal = round($order['goods_price'] * (1+$entrust_rate/100),2);
        if($entrust_price){
            $entrust_price <= 0 && $this->error('上架价格不能小于等于0');
            $entrust_price > $entrust_price_cal && $this->error('上架价格不可多于购买价格的%'.$entrust_rate);
        }else{
            $entrust_price = $entrust_price_cal;
        }
        //手续费
        $service_rate = config('site.service_rate');
        $service_fee = round($order['goods_price'] * ($service_rate/100),2);
        //优惠券抵扣
        $coupon_price = 0;
        $pay_price = $service_fee;
        if($user_coupon_id){
            $user_coupon = UserCoupon::where('user_id',$this->auth->id)
                ->where('end_time','>',time())
                ->where('status',1)
                ->where('id',$user_coupon_id)
                ->find();
            empty($user_coupon) && $this->error('优惠券不存在');
            $pay_price < $user_coupon['bottom_price'] && $this->error('委托费用不能低于优惠券使用门槛');
            $coupon_price = $user_coupon['price'];
            $pay_price = round($pay_price-$coupon_price,2);
        }
        ($pay_price > 0 && empty($openid)) && $this->error('缺少openid');
        $out_trade_no = get_order_sn('E');
        //创建委托订单
        $entrust = RushOrderEntrust::create([
            'entrust_no' => $out_trade_no,
            'entrust_price' => $entrust_price,
            'service_fee' => $service_fee,
            'coupon_price' => $coupon_price,
            'pay_price' => $pay_price,
            'user_coupon_id' => $user_coupon_id?:0,
            //记录抢购订单数据
            'order_id' => $order['id'],
            'order_no' => $order['order_no'],
            'goods_price' => $order['goods_price'],
        ]);
        if($pay_price > 0){
            $notifyurl = $this->request->root(true) . '/api/rush_buyer/entrustNotify/paytype/wechat';
            $result = Service::submitOrder($pay_price, $out_trade_no, "wechat", "抢购订单支付", $notifyurl, "", "mp",$openid);
        }else{
            //处理订单
            $res = self::entrustNotifyAction($entrust,$order,'');
            $res['code'] == 0 && $this->error($res['msg']);
        }
        $result['order_id'] = $order_id;
        $this->success( '预支付', $result );
    }

    /**
     * @ApiTitle    (委托上架-异步)
     * @ApiInternal
     */
    public function entrustNotify()
    {
        $paytype = $this->request->param('paytype');
        $pay = Service::checkNotify($paytype);
        if (!$pay) {
            echo '签名错误';
            return;
        }
        $data = $pay->verify();
        \think\Log::write('entrustNotify微信支付异步参数：'.json_encode($data));
        try {
            //$payamount = $paytype == 'alipay' ? $data['total_amount'] : $data['total_fee'] / 100;
            $out_trade_no = $data['out_trade_no'];
            //委托订单
            $entrust = RushOrderEntrust::where('entrust_no',$out_trade_no)->find();
            //抢购订单
            $rush_order = RushOrder::get($entrust['order_id']);
            if (!$entrust) { // 如果订单不存在
                echo $pay->success(); // 告诉微信，我已经处理完了，订单没找到，别再通知我了
            }
            // 检查订单是否已经更新过支付状态
            if ($entrust['pay_status'] != '0') {
                echo $pay->success(); // 已经支付成功了就不再更新了
            }
            //处理订单
            self::entrustNotifyAction($entrust,$rush_order,$data['transaction_id']);
        } catch (Exception $e) {
            \think\Log::write('entrustNotify错误：'.$e->getMessage());
        }
        echo $pay->success();
    }

    /**
     * 委托上架-异步操作
     * @ApiInternal
     */
    public static function entrustNotifyAction($entrust,$rush_order,$transaction_id){
        $new_order_no = get_order_sn('R'.mt_rand(0000,9999));
        Db::startTrans();
        try{
            //委托订单状态变为：已支付
            $entrust->save([
                'pay_status' => '1',
                'pay_time' => time(),
                'transaction_id' => $transaction_id
            ]);
            \think\Log::write('【1】没有问题');
            //生成新抢购单
            $new_order = RushOrder::create([
                'seller_id' => $rush_order['buyer_id'],
                'order_no' => $new_order_no,
                'order_status' => '3', //状态直接设置为已委托上架
                'goods_id' => $rush_order['goods_id'],
                'goods_name' => $rush_order['goods_name'],
                'goods_no' => $rush_order['goods_no'],
                'goods_price' => $entrust['entrust_price'], //新价格
                'goods_image' => $rush_order->getData('goods_image'),
                'time_id' => $rush_order['time_id'],
                'time_name' => RushTime::where('id',$rush_order['time_id'])->value('name'),
            ]);
            \think\Log::write('【2】没有问题');
            //抢购订单状态变为：已上架转移，记录新抢购订单ID
            $rush_order->save([
                'order_status'=>'5',
                'new_order_id' => $new_order['id']
            ]);
            \think\Log::write('【3】没有问题');
            //商品状态变为：已上架，更换卖家、抢购价、当前订单ID
            RushGoods::where('id',$rush_order['goods_id'])->update([
                'seller_id' => $rush_order['buyer_id'],
                'buyer_id' => 0,
                'current_order_id' => $new_order['id'],
                'current_price' => $entrust['entrust_price'],
                'status' => '1',
            ]);
            \think\Log::write('【4】没有问题');
            //优惠券状态变为：已使用
            if($entrust['user_coupon_id']){
                UserCoupon::where('id',$entrust['user_coupon_id'])->update(['use_time'=>time(),'status'=>2]);
            }
            \think\Log::write('【5】没有问题');
            Db::commit();
        }catch (PDOException $e){
            Db::rollback();
            \think\Log::write('entrustNotifyAction错误：'.$e->getMessage());
            \think\Log::write('新订单号：'.$new_order_no);
            return ['code' => 0,'msg' => $e->getMessage()];
        }catch (Exception $e){
            Db::rollback();
            \think\Log::write('entrustNotifyAction错误：'.$e->getMessage());
            \think\Log::write('新订单号：'.$new_order_no);
            return ['code' => 0,'msg' => $e->getMessage()];
        }
        return ['code' => 1,'msg' => '成功'];
    }

    /**
     * @ApiTitle    (提货-订单展示)
     * @ApiMethod   (GET)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name=order_id, type=integer, required=true, description="订单ID")
     * @ApiReturn   ({
        "code": 1,
        "msg": "",
        "time": "1652254547",
        "data": {
            "id": 3, //订单ID
            "order_no": "R2022051154100974", //订单号
            "order_status": "0", //订单状态:0=待付款,1=待确认收款,2=待委托上架（待提货）,3=买家已委托上架,4=已提货,11=已取消
            "goods_name": "商品一", //商品名称
            "goods_price": "7000.00", //商品价格
            "goods_image": "http://petsdemo.qiniu.brofirst.cn/uploads/20220508/13cb1b8e54988cbb3710cc79897f0096.jpg", //封面图
            "time_name": "狂欢上午场", //所属场次
            "seller": { //交易方
                "id": 1000, //ID
                "nickname": "Xue", //昵称
                "avatar": "", //头像
                "url": "/u/1000"
            },
            "order_status_text": "Order_status 0", //订单状态文字
            "complain_status_text": "Complain_status 0"
        }
    })
     */
    public function takeoverView()
    {
        $order_id = $this->request->param('order_id');
        empty($order_id) && $this->error('请选择订单');
        $order = RushOrder::where('buyer_id',$this->auth->id)->where('id',$order_id)->find();
        empty($order) && $this->error('订单不存在');
        $order->visible(['id','order_no','order_status','goods_name','goods_image','goods_price','time_name','seller']);
        $order['seller']->visible(['id','avatar','nickname']);
        $this->success('',$order);
    }

    /**
     * @ApiTitle    (提货)
     * @ApiMethod   (GET)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name=order_id, type=integer, required=true, description="订单ID")
     * @ApiParams   (name=address_id, type=integer, required=true, description="地址ID")
     * @ApiReturn   ({
        "code":"状态码",
        "msg": "提示消息"
    })
     */
    public function takeover()
    {
        $order_id = $this->request->param('order_id');
        $address_id = $this->request->param('address_id');
        empty($order_id) && $this->error('请选择订单');
        empty($address_id) && $this->error('请选择地址');
        $order = RushOrder::where('buyer_id',$this->auth->id)->where('id',$order_id)->field('id,order_status,buyer_id')->find();
        empty($order) && $this->error('订单不存在');
        $order['order_status'] != '2' && $this->error('订单不合法');
        $address = UserAddress::where('user_id',$this->auth->id)->where('id',$address_id)->find();
        empty($address) && $this->error('地址不存在');
        Db::startTrans();
        try{
            //抢购订单状态变为：已提货（已完成）
            $order->save(['order_status' => '4']);
            //记录提货地址
            RushOrderAddress::create([
                'order_id' => $order_id,
                'user_id' => $order['buyer_id'],
                'name' => $address['name'],
                'mobile' => $address['mobile'],
                'address_now' => $address['address_now'],
                'address' => $address['address'],
                'is_default' => $address['is_default'],
                'province_id' => $address['province_id'],
                'city_id' => $address['city_id'],
                'region_id' => $address['region_id'],
                'province' => $address['province'],
                'city' => $address['city'],
                'region' => $address['region'],
            ]);
            Db::commit();
        }catch (PDOException $e){
            Db::rollback();
            $this->error($e->getMessage());
        }catch (Exception $e){
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('');
    }

    /**
     * @ApiTitle    (提货-取消)
     * @ApiMethod   (GET)
     * @ApiReturn   ({
        "code": 1,
        "msg": "",
        "time": "1652254547",
        "data": null
    })
     */
    public function takeoverCancel()
    {
        $order_id = $this->request->param('order_id');
        empty($order_id) && $this->error('请选择订单');
        $order = RushOrder::where('buyer_id',$this->auth->id)->where('id',$order_id)->field('id,order_status,express_company,express_no')->find();
        empty($order) && $this->error('订单不存在');
        $order['order_status'] != '4' && $this->error('订单不合法');
        $res = self::takeoverCancelAction($order);
        $res['code'] == 0 && $this->error($res['msg']);
        $this->success('成功');
    }

    /**
     * 取消提货操作
     * @ApiInternal
     */
    public static function takeoverCancelAction($order)
    {
        Db::startTrans();
        try {
            //订单状态变为：待委托上架
            $order->save(['order_status' => '2','express_company'=>'','express_no'=>'']);
            //删除提货时填写的地址
            RushOrderAddress::where('order_id',$order['id'])->delete();
            Db::commit();
        }catch (PDOException $e){
            Db::rollback();
            return ['code' => 0,'msg' => $e->getMessage()];
        }catch (Exception $e){
            Db::rollback();
            return ['code' => 0,'msg' => $e->getMessage()];
        }
        return ['code' => 1,'msg' => '取消提货成功'];
    }

    /**
     * @ApiTitle    (查看物流)
     * @ApiMethod   (GET)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name=order_id, type=integer, required=true, description="订单ID")
     * @ApiReturn   ({
        "code": 1,
        "msg": "",
        "time": "1652254547",
        "data": {
            "express_company": "快递公司", //快递公司
            "express_no": "快递单号", //快递单号
        }
    })
     */
    public function express()
    {
        $order_id = $this->request->param('order_id');
        empty($order_id) && $this->error('请选择订单');
        $order = RushOrder::where('buyer_id',$this->auth->id)
            ->where('id',$order_id)
            ->field('express_company,express_no')
            ->find();
        empty($order) && $this->error('订单不存在');
        $this->success('',$order);
    }
}
